package mark.tom.friend.base.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.IntDef;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import mark.tom.friend.base.util.SnackBarUtil;
import mark.tom.friend.roll.R;
import timber.log.Timber;

public abstract class BaseActivity extends RxAppCompatActivity {

    // mExistTime为记录第一次按返回键的时间
    protected long mExitTime;
    // statusBar高度
    protected int statusBarHeight;
    // ToolBar高度
    protected int toolBarHeight = 0;
    // 返回键点击效果
    @BackWayEnums protected int backOperation = BACK_WAY_CLICK;

    @Override
    @CallSuper
    protected void onCreate(Bundle savedInstanceState) {
        // 设置是否有标题
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 强制竖屏
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 设置是否全屏
        if (isFullScreen()) {
            this.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        super.onCreate(savedInstanceState);
        // 打印日志
        printLog("onCreate");
        ViewGroup container = getWindow().getDecorView().findViewById(android.R.id.content);
        View contentView = getLayoutInflater().inflate(getLayoutId(), container, false);
        // 设置当前的视图
        this.setContentView(contentView);
        // 开启透明模式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isTransparentMode()) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(android.R.color.transparent);
            statusBarHeight = tintManager.getConfig().getStatusBarHeight();
        }
        onCreate(contentView, savedInstanceState);
    }

    protected boolean isFullScreen() {
        return false;
    }

    protected boolean isTransparentMode() {
        return true;
    }

    protected void setBackAwayMode(@BackWayEnums int backAwayEnum) {
        this.backOperation = backAwayEnum;
    }

    protected abstract int getLayoutId();

    protected abstract void onCreate(View contentView, Bundle savedInstanceState);

    protected void setToolBar(Toolbar toolBar) {
        setToolBar(toolBar, R.mipmap.app_toolbar_back);
    }

    protected void setToolBar(Toolbar toolBar, int navigationIconId) {
        if (toolBar == null) {
            return;
        }
        // 如果Android版本大于4.4则采用沉浸式,需要重设toolbar高度
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && statusBarHeight != 0) {
            int h = toolBar.getLayoutParams().height;
            toolBarHeight = h + statusBarHeight;
            toolBar.getLayoutParams().height = toolBarHeight;
            int pB = toolBar.getPaddingBottom();
            int pT = toolBar.getPaddingTop();
            int pL = toolBar.getPaddingLeft();
            int pR = toolBar.getPaddingRight();
            toolBar.setPadding(pL, pT + statusBarHeight, pR, pB);
        } else {
            toolBarHeight = toolBar.getLayoutParams().height;
        }
        // 设置左图标和其点击事件
        if (backOperation == BACK_WAY_CLICK || backOperation == BACK_WAY_CONFIRM) {
            // 设置ToolBar背景色
            try {
                toolBar.setNavigationIcon(navigationIconId);
            } catch (Exception ex) {
                toolBar.setNavigationIcon(R.mipmap.app_toolbar_back);
            }
        }
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (backOperation == BACK_WAY_CLICK) {
                    finish();
                } else if (backOperation == BACK_WAY_CONFIRM) {
                    backConfirmEvent();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        // 打印日志
        printLog("onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        // 打印日志
        printLog("onPause");
    }

    @Override
    public void finish() {
        super.finish();
        // 打印日志
        printLog("onFinish");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 打印日志
        printLog("onDestroy");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 打印日志
        printLog("onNewIntent");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 打印日志
        printLog("onSaveInstanceState");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (backOperation == BACK_WAY_DOUBLE) {
                // 按两下返回键退出应用
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    SnackBarUtil.showSnackBar(this, R.string.app_exit_warn);
                    mExitTime = System.currentTimeMillis();
                } else {
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            } else if (backOperation == BACK_WAY_MINIMIZE) {
                // 最小化应用
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else if (backOperation == BACK_WAY_CONFIRM) {
                // 退出当前界面需要确认
                backConfirmEvent();
            } else {
                // 直接退出当前界面
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void printLog(String methodName) {
        Timber.d(getTag() + ":" + methodName);
    }

    protected String getTag() {
        return this.getLocalClassName();
    }

    protected void backConfirmEvent() {
        // 重写此方法，以满足不同的需求
    }

    protected static final int BACK_WAY_DOUBLE = 0;
    protected static final int BACK_WAY_CLICK = 1;
    protected static final int BACK_WAY_CONFIRM = 2;
    protected static final int BACK_WAY_MINIMIZE = 3;

    @IntDef({
            BACK_WAY_DOUBLE,
            BACK_WAY_CLICK,
            BACK_WAY_CONFIRM,
            BACK_WAY_MINIMIZE
    })
    @Retention(RetentionPolicy.SOURCE)
    private @interface BackWayEnums {
    }
}
